﻿using System;
using System.Windows.Forms;
using ChatClientApp.Classes;

namespace ChatClientApp.GUI
{
    public partial class fLogin : Form
    {
        public delegate void SendMessageEventHandler(object sender, MessageEventArgs mEA);
        public static event SendMessageEventHandler OnSendMessageHandler;

        private bool isButtonPushed;
        private string triedNickname;

        public fLogin()
        {
            isButtonPushed = false;
            InitializeComponent();
        }

        public string getTriedNick()
        {
            if (triedNickname != String.Empty)
                return triedNickname;
            else
                return String.Empty;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            isButtonPushed = true;
            triedNickname = textBox1.Text;
            try
            {
                string message = ServerHandling.Login(textBox1.Text, textBox2.Text);
                if (message.ToLower().Contains("accepted"))
                {
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("Could not connect as: " + triedNickname + Tools.Tools.NL + "Not registered or Server down.");
                    this.DialogResult = DialogResult.Retry;
                }
                /*
                cl = null;
                cl = new ChatClient.ClientClass(textBox1.Text, textBox2.Text);
                cl.ServerPort = (ActiveComponents.ActiveServerPort);
                cl.Login();

                while (!cl.FinishedLogin)
                {
                    ;
                }

                if (cl.IsLogedIn)
                    this.DialogResult = DialogResult.OK;
                else
                    this.DialogResult = DialogResult.Retry;
                */
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.Retry;
            }
        }

        private void raiseEvent(String mess)
        {
            this.OnSendMessage(new MessageEventArgs(mess));
        }

        protected void OnSendMessage(MessageEventArgs e)
        {
            if (OnSendMessageHandler != null)
                OnSendMessageHandler(this, e);
        }

        private void CCA_Login_OnSendMessageHandler(object sender, MessageEventArgs e)
        {
            this.OnSendMessage(e);
        }

        private void CCA_Login_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!isButtonPushed)
            {
                this.DialogResult = DialogResult.Abort;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            fRegistration reg = new fRegistration();
            reg.Show();
        }
    }
}
